package services;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import models.UploadLog;
import models.User;
import play.libs.XML;
import utils.Base64Util;
import utils.BizConstants;
import utils.UrlUtils;
import vos.AppDataVo;

public class UploadToAppService {
	/**
	 * 上传pdf到app
	 *
	 * @Title: uploadToApp 
	 * @param pdf
	 * @param organization
	 * @param idcard
	 * @param pdfname 
	 * @return
	 * @return: boolean
	 */
	public static boolean uploadToApp(File pdf, String organization, String idcard, String pdfname,String checkDate) {
		// TODO Auto-generated method stub
		User u=User.findById(idcard);
		if(StringUtils.isEmpty(u.phone)||StringUtils.isEmpty(organization)){
			return false;
		}
		u.password=u.idcard.substring(u.idcard.length()-6,u.idcard.length());
		AppDataVo vo=new AppDataVo(u.idcard,u.password,u.birthdate,u.username,
				u.sex,u.phone,u.bloodtype,"",organization,checkDate,0);
		vo.ReportPdf=readPdf(pdf);
		if("男".equals(vo.Sex)){
			vo.Sex="1";
		}
		else if("女".equals(vo.Sex)){
			vo.Sex="2";
		}
		else{
			vo.Sex="0";
		}
		//vo.Username=vo.Bloodtype;
		if("不知道".equals(vo.Bloodtype)){
			vo.Bloodtype="";
		}
		vo.Username=Base64Util.encode(vo.Username.getBytes());
		return UrlUtils.url(BizConstants.UPLOAD_ADD_URL, vo,pdfname);
		//return upload(vo,pdfname);
	}
	/**
	 * 上传数据
	 *
	 * @Title: upload 
	 * @param vo
	 * @param pdfname 
	 * @return
	 * @return: boolean
	 */
	public static boolean upload(AppDataVo vo, String pdfname) {
		// TODO Auto-generated method stub
		String json=JSON.toJSONString(vo);
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,20000);//连接时间
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,20000);//数据传输时间
		String res="";
		try {
			HttpPost httppost = new HttpPost(BizConstants.UPLOAD_ADD_URL);
			//httppost.setHeader("Content-Type", "text/json"); 
			Charset chars = Charset.forName("UTF-8");
			MultipartEntity reqEntity = new MultipartEntity();
			System.out.println(json.getBytes().length);
			StringBody comment =StringBody.create(json, "text/json", chars);
			//StringBody comment = new StringBody(json, chars);
			reqEntity.addPart("userinfo",comment);
			httppost.setEntity(reqEntity);
			HttpResponse response = httpclient.execute(httppost);
			res=EntityUtils.toString(response.getEntity());
			if(res.length()>=500){
				res="返回参数过长";
			}
			if(response.getStatusLine().getStatusCode()==200){
				//String res=EntityUtils.toString(response.getEntity());
				JSONObject result= JSON.parseObject(res);
				Integer state=(Integer)result.get("StateCode");
				String msg=(String)result.get("Msg");
				String value=(String)result.get("Value");
				UploadLog log=new UploadLog(pdfname,state,msg,value,new Date(),res);
				//保存上传日志
				UploadLogService.saveLog(log);
				if(state==1){
					return true;
				}
				else{
					return false;
				}
			}
			else{
				//网络错误保存
				UploadLog log=new UploadLog(pdfname,999,"网络错误","",new Date(),Integer.toString(response.getStatusLine().getStatusCode()));
				UploadLogService.saveLog(log);
				return false;
			}
		}catch(Exception e){
			UploadLog log=new UploadLog(pdfname,999,"系统异常","",new Date(),res);
			UploadLogService.saveLog(log);
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 将文件进行base64加密
	 *
	 * @Title: readPdf 
	 * @param pdf
	 * @return
	 * @return: String
	 */
	public static String readPdf(File pdf){
		byte b[] = new byte[(int) pdf.length()];
		try{
			InputStream input = new FileInputStream(pdf);
			input.read(b);
			input.close();
		}catch(IOException e){
			e.printStackTrace();
			return null;
		}
		return Base64Util.encode(b);
	}
}
